<template>
  <div class="app-container">
    <!-- Tab页签 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="我收到的" name="received">
        <div class="header-bar" style="justify-content:space-between">
          <el-button type="primary" icon="Plus" @click="handleSendMessage"> 发送消息 </el-button>
          <el-input
            placeholder="请输入消息标题/内容"
            style="width: 250px; float: right; margin-bottom: 10px;" 
            v-model="receivedQuery.keyword"
            @keyup.enter="handleReciveSearch"
            clearable
          >
            <template #append>
              <el-button icon="Search" @click="handleReciveSearch"></el-button>
            </template>
          </el-input>
        </div>
        <!-- 收到的消息表格 -->
        <el-table v-loading="receivedLoading" :data="receivedList" border style="width: 100%">
          <el-table-column prop="messageTitle" label="消息标题" min-width="150" show-overflow-tooltip />
          <el-table-column prop="messageContentAbbr" label="消息内容" min-width="150" show-overflow-tooltip />
          <el-table-column prop="messageType" label="消息类型">
            <template #default="scope">
              <el-tag :type="scope.row.messageType === 'S' ? 'success' : 'info'">
                {{ scope.row.messageType === 'S' ? '系统消息' : '用户消息' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isRead" label="当前状态">
            <template #default="scope">
              <el-tag :type="scope.row.isRead === '0' ? 'warning' : 'success'">
                {{ scope.row.isRead === '0' ? '未读' : '已读' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="senderName" label="发送人" />
          <el-table-column prop="createTime" label="发送时间"/>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" link @click="handleInfoDetails(scope.row, 'recived')">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="receivedQuery.pageNum"
            v-model:page-size="receivedQuery.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="receivedTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleReceivedSizeChange"
            @current-change="handleReceivedCurrentChange"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane label="我发送的" name="sent">
        <div class="header-bar" style="justify-content: space-between;">
          <el-button type="primary" icon="Plus" @click="handleSendMessage"> 发送消息 </el-button>
          <el-input
            placeholder="请输入消息标题/内容"
            style="width: 250px; float: right; margin-bottom: 10px;" 
            v-model="sentQuery.keyword"
            @keyup.enter="handleSendSearch"
            clearable
          >
            <template #append>
              <el-button icon="Search" @click="handleSendSearch"></el-button>
            </template>
          </el-input>
        </div>
        <!-- 发送的消息表格 -->
        <el-table v-loading="sentLoading" :data="sentList" border style="width: 100%">
          <el-table-column prop="messageTitle" label="消息标题" min-width="150" show-overflow-tooltip />
          <el-table-column prop="messageContentAbbr" label="消息内容" min-width="150" show-overflow-tooltip/>
          <el-table-column prop="status" label="当前状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === '发送成功' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="receivers" label="下发对象" show-overflow-tooltip />
          <el-table-column prop="createTime" label="发送时间" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" link @click="handleInfoDetails(scope.row, 'send')">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="sentQuery.pageNum"
            v-model:page-size="sentQuery.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="sentTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSentSizeChange"
            @current-change="handleSentCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 发送消息弹窗 -->
    <el-dialog
      v-model="sendMessageVisible"
      title="发送消息"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="sendMessageFormRef"
        :model="sendMessageForm"
        :rules="sendMessageRules"
        label-width="100px"
      >
        <el-descriptions :column="1" border class="custom-descriptions">
          <el-descriptions-item label="*消息标题" prop="messageTitle">
            <el-form-item prop="messageTitle">
              <el-input
                v-model="sendMessageForm.messageTitle"
                placeholder="支持1~128个字符"
                maxlength="128"
                show-word-limit
              />
            </el-form-item> 
          </el-descriptions-item>
          <el-descriptions-item label="*下发对象" prop="receiveUserIds">
            <div style="display: flex; gap: 10px;">
              <el-form-item style="flex: 1; margin-bottom: 0;">
                <el-tree-select
                  v-model="treeDeptId"
                  :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  value-key="id"
                  placeholder="请选择归属部门"
                  check-strictly
                  @node-click="handleNodeClick"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item prop="receiveUserIds" style="flex: 1; margin-bottom: 0;">
                <el-select
                  v-model="sendMessageForm.receiveUserIds"
                  multiple
                  collapse-tags
                  clearable
                  placeholder="请选择用户"
                  style="width: 100%"
                >
                  <template #header>
                    <el-checkbox v-model="selectAllUsers"
                      :indeterminate="isIndeterminate"
                      @change="handleSelectAllChange"
                      style="margin-left: 10px"
                    >
                      全选
                    </el-checkbox>
                  </template>
                  <el-option
                    v-for="user in userOptions"
                    :key="user.userId"
                    :label="user.nickName || user.userName"
                    :value="user.userId"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="*消息内容" :rowspan="4">
            <el-form-item prop="messageContentAbbr">
              <el-input
                v-model="sendMessageForm.messageContentAbbr"
                type="textarea"
                :rows="6"
                placeholder="支持1~5000个字符"
                maxlength="5000"
                show-word-limit
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="附件" >
            <el-form-item prop="attachment">
              <el-upload
                ref="uploadRef"
                :limit="1"
                accept=".doc, .xlsx, .pdf, .ppt, .zip"
                :auto-upload="false"
                :before-upload="handleBeforeUpload"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :on-remove="handleRemove"
                :on-change="handleImportFileChange"
                :on-exceed="handleExceed"
                :file-list="fileList"
              >
                <template #default>
                  <el-button type="primary" icon="Upload">上传文件</el-button>
                  <div class="el-upload__tip">支持格式doc、xlsx、pdf、ppt、zip</div>
                </template>
                <template #progress>
                  <div class="el-upload-progress">
                    <el-progress
                      :percentage="uploadPercentage"
                      :stroke-width="6"
                      :show-text="true"
                    />
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sendMessageVisible = false">取消</el-button>
          <el-button type="primary" :loading="sendLoading" @click="handleSendSubmit">
            发送
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog
      v-model="viewDetailsVisible"
      title="查看详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="1" border class="custom-descriptions">
        <el-descriptions-item label="消息标题">
          {{ currentMessage.messageTitle }}
        </el-descriptions-item>
        <el-descriptions-item label="消息类型">
          <el-tag :type="currentMessage.messageType === 'S' ? 'success' : 'info'">
            {{ currentMessage.messageType === 'S' ? '系统消息' : '用户消息' }}
          </el-tag>
        </el-descriptions-item>
        <!-- 我收到的：显示发送人 -->
        <el-descriptions-item v-if="activeTab === 'received'" label="发送人">
          {{ currentMessage.senderName }}
        </el-descriptions-item>
        <!-- 我发送的：显示下发对象 -->
        <el-descriptions-item v-if="activeTab === 'sent'" label="下发对象" :rowspan="6">
          <!-- <div class="recipient-info">
            <span>{{ currentMessage.senderAccount }}</span>
          </div> -->
          <el-table :data="recipientList" border style="width: 100%">
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="deptPath" label="所属部门" />
          </el-table>
          <!-- 分页 -->
          <div class="pagination-container" style="margin-top: 10px; text-align: right">
            <el-pagination
              v-model:current-page="recipientPageNum"
              v-model:page-size="recipientPageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="recipientTotal || 0"
              layout="total, sizes, prev, next,"
            />
            <!-- @size-change="handleRecipientSizeChange"
            @current-change="handleRecipientCurrentChange" -->
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="发送时间">
          {{ currentMessage.createTime }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentMessage.fileName" label="附件" :span="2">
          <span style="margin-left: 10px; margin-right: 10px;">{{ currentMessage.fileName }}</span>
          <el-link type="primary" @click="handleControlAttachment('preview', currentMessage.filePath, currentMessage.fileName)">预览</el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" @click="handleControlAttachment('download', currentMessage.filePath, currentMessage.fileName)"> 下载 </el-link>
        </el-descriptions-item>
        <el-descriptions-item label="消息内容" :rowspan="4">
          <div class="message-content">
            {{ currentMessage.messageContent }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeViewDetails">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog
      v-model="viewFileVisible"
      title="文件预览"
      width="800px"
      @close="viewFileVisible = false"
    >
      <!-- <VueOfficeExcel
        :src="filePath.value"
        style="width: 100%; height: 500px;"
      /> -->
      11111
    </el-dialog>
  </div>
</template>

<script setup name="messageCenter">
import { ref, reactive, onMounted, watch } from 'vue'
import VueOfficeExcel from '@vue-office/excel';
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserId } from '@/utils/auth' // 导入获取角色的方法
import {
  sendMessage,
  reciveMessageList,
  reciveMessageDetail,
  sendMessageList,
  commonUploadFile,
  sendMessageDetail,
  downloadAttachment,
  getSentMessageReceiverList
} from '@/api/personCenter'
import {
  listUser,
  deptTreeSelect
} from '@/api/system/user'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

// 当前激活的tab
const activeTab = ref('received')
const userStore = useUserStore()

// 收到的消息相关数据
const receivedLoading = ref(false)
const receivedList = ref([])
const receivedTotal = ref(0)
const receivedQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
})
// 全选状态
const selectAllUsers = ref(false)
// 半选状态
const isIndeterminate = ref(false)
// 部门树form
const treeDeptId = ref('')
// 部门树源数据
const deptOptions = ref(undefined)
// 人员源数据
const userOptions = ref(undefined)

// 发送的消息相关数据
const sentLoading = ref(false)
const sentList = ref([])
const sentTotal = ref(0)
const sentQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
})

// 发送消息弹窗
const sendMessageVisible = ref(false)
const sendMessageFormRef = ref()
const sendLoading = ref(false)
const sendMessageForm = reactive({
  messageTitle: '',
  receiveUserIds: [],
  messageContentAbbr: '',
  attachment: null
})

const sendMessageRules = {
  messageTitle: [
    { required: true, message: '请输入消息标题', trigger: 'blur' },
    { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }
  ],
  receiveUserIds: [{ required: true, message: '请选择下发对象', trigger: 'change' }],
  messageContentAbbr: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { min: 1, max: 5000, message: '长度在 1 到 5000 个字符', trigger: 'blur' }
  ],

}

// 文件上传
const upload = reactive({
  // 是否显示弹出层（Excel导入）
  open: false,
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  // url: import.meta.env.VITE_APP_BASE_API + '/common/uploadMinio'
})
const fileList = ref([])
const importFile = ref(null)
// el-upload组件引用
const uploadRef = ref(null)

// 查看详情弹窗
const viewDetailsVisible = ref(false)
const currentMessage = ref(null)
const recipientList = ref([])
const recipientTotal = ref(0)
// 文件预览弹窗
const viewFileVisible = ref(false)
const filePath = ref('')
// 接收人列表分页
const recipientPageNum = ref(1)
const recipientPageSize = ref(10)

// 监听用户选择变化
watch(() => sendMessageForm.receiveUserIds, () => {
  updateSelectAllState()
}, { deep: true })
// Tab切换
const handleTabClick = (tab) => {
  if (tab.paneName === 'sent') {
    getSentList()
  } else {
    getReceivedList()
  }
}
const getDeptTree = async () => {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data
  })
}

// 部门树节点点击事件
const handleNodeClick = (data) => {
  treeDeptId.value = data.id
  // 清空人员列表
  userOptions.value = []
  // 重置全选状态
  selectAllUsers.value = false
  isIndeterminate.value = false
  // 查询部门下的人员
  listUser({ deptId: treeDeptId.value, pageNum: 1, pageSize: 1000 }).then(res => {
    if (res.code === 200) {
      userOptions.value = res?.rows || []
      // 计算当前部门的用户选中状态
      updateSelectAllState()
    } else {
      userOptions.value = []
    }
    // 重置选择状态
    selectAllUsers.value = false
    isIndeterminate.value = false
  })
}

// 处理全选变化
const handleSelectAllChange = (value) => {
  if (!userOptions.value || userOptions.value.length === 0) return
  
  selectAllUsers.value = value
  isIndeterminate.value = false
  
  // 获取当前部门所有用户的userId
  const deptUserIds = userOptions.value.map(user => user.userId)
  
  if (value) {
    // 全选：添加当前部门所有未选中的用户
    deptUserIds.forEach(userId => {
      if (!sendMessageForm.receiveUserIds.includes(userId)) {
        sendMessageForm.receiveUserIds.push(userId)
      }
    })
  } else {
    // 取消全选：移除当前部门所有选中的用户
    sendMessageForm.receiveUserIds = sendMessageForm.receiveUserIds.filter(
      id => !deptUserIds.includes(id)
    )
  }
}

// 更新全选状态
const updateSelectAllState = () => {
  if (!userOptions.value || userOptions.value.length === 0) {
    selectAllUsers.value = false
    isIndeterminate.value = false
    return
  }
  
  const deptUserIds = userOptions.value.map(user => user.userId)
  const selectedDeptUserIds = deptUserIds.filter(id => 
    sendMessageForm.receiveUserIds.includes(id)
  )
  
  selectAllUsers.value = selectedDeptUserIds.length === deptUserIds.length
  isIndeterminate.value = selectedDeptUserIds.length > 0 &&  selectedDeptUserIds.length < deptUserIds.length
}

// 获取收到的消息列表
const getReceivedList = async () => {
  receivedLoading.value = true
  reciveMessageList(receivedQuery).then(res => { 
    if (res.code === 200) {
      receivedList.value = res.data?.list || []
      receivedTotal.value = res.data?.total || 0
    } else {
      ElMessage.error(res.msg || '获取消息列表失败')
    }
  }).finally(() => {
    receivedLoading.value = false
  })
}

// 获取发送的消息列表
const getSentList = async () => {
  sentLoading.value = true
  sendMessageList(sentQuery).then(res => {
    if (res.code === 200) {
      sentList.value = res.data?.list || []
      sentTotal.value = res.data?.total || 0
    } else {
      ElMessage.error(res.msg || '获取消息列表失败')
    }
  }).finally(() => {
    sentLoading.value = false
  })
}

// 收到的消息搜索
const handleReciveSearch = () => {
  receivedQuery.pageNum = 1
  getReceivedList()
}

// 发送的消息搜索
const handleSendSearch = () => {
  sentQuery.pageNum = 1
  getSentList()
}

// 收到的消息分页
const handleReceivedSizeChange = (val) => {
  receivedQuery.pageSize = val
  getReceivedList()
}

const handleReceivedCurrentChange = (val) => {
  receivedQuery.pageNum = val
  getReceivedList()
}

// 发送的消息分页
const handleSentSizeChange = (val) => {
  sentQuery.pageSize = val
  getSentList()
}

const handleSentCurrentChange = (val) => {
  sentQuery.pageNum = val
  getSentList()
}

// 发送消息
const handleSendMessage = () => {
  sendMessageVisible.value = true
  // 重置表单
  Object.assign(sendMessageForm, {
    messageTitle: '',
    receiveUserIds: [],
    messageContentAbbr: '',
    attachment: null
  })
  fileList.value = []
  // 重置全选和半选状态
  selectAllUsers.value = false
  isIndeterminate.value = false
  // 重置部门树选择
  treeDeptId.value = ''
  // 重置用户列表
  userOptions.value = []
}

// 处理文件选择前的校验
const handleBeforeUpload = (file) => {
  // 检查文件类型
  const isValidType = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
  if (!isValidType) {
    ElMessage.warning('仅支持.xlsx和.xls格式文件')
    return false
  }
  
  // 检查文件大小（可选）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.warning('文件大小不能超过2MB')
    return false
  }
  
  return true
}
// 处理文件上传中
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
// 处理文件上传成功
function handleFileSuccess(response, file, fileList) {
  console.log('文件上传成功:', file.name, response)
}
function handleImportFileChange(uploadFile, uploadFiles) {
  importFile.value = uploadFile.raw
  fileList.value = uploadFiles
}
function handleExceed(files, uploadFiles) {
  // 直接用新文件替换第一个文件
  fileList.value = [files[files.length - 1]]
  importFile.value = fileList.value[0]?.raw || null
}
// 处理文件移除
function handleRemove(file) {
  // 更新本地文件列表
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

// 发送消息提交
const handleSendSubmit = async () => {
  // 表单校验
  if (!sendMessageFormRef.value) return
  try {
    await sendMessageFormRef.value.validate()
    // 校验通过，准备提交数据
    sendLoading.value = true
    // console.log('提交数据:', sendMessageForm);
    upload.isUploading = true
    const messageType = getUserId()
    try {
      const formData = new FormData()
      formData.append('messageTitle', sendMessageForm.messageTitle)
      formData.append('messageType', messageType === '1' ? 'S' : 'U')
      formData.append('messageContent', sendMessageForm.messageContentAbbr)
      formData.append('file', importFile.value)
      sendMessageForm?.receiveUserIds?.forEach(userId => {
        formData.append('receiveUserIds', userId)
      })
      // 调用通用上传接口
      sendMessage(formData).then(res => {
        if (res.code === 200) {
          ElMessage.success(res.data)
          // 关闭弹窗
          sendLoading.value = false
          // 清空文件列表
          fileList.value = []
          importFile.value = null
          sendMessageVisible.value = false
          // 刷新客户列表
          getReceivedList()
          userStore.setUserInfo()
        }
      }).catch(() => {
      })
    } catch (error) {
    } finally {
      upload.isUploading = false
    }
  } catch (error) {
  } finally {
    sendLoading.value = false
  }
}

// 查看收到的消息详情
const handleInfoDetails = (row, infoType) => {
  if (infoType === 'recived') { 
    reciveMessageDetail(row.id).then(res => {
      if (res.code === 200) {
        currentMessage.value = { ...res.data }
        viewDetailsVisible.value = true
        getReceivedList()
      }
    }).catch(() => {
    })
  } else {
    sendMessageDetail(row.id).then(res => {
      if (res.code === 200) {
        currentMessage.value = { ...res.data }
        getSentMessageReceiverList({
          messageId: row.id
        }).then(res => {
          if (res.code === 200) {
            recipientList.value = res.data?.list || []
            recipientTotal.value = res.data?.total || 0
          }
        })
        viewDetailsVisible.value = true
      }
    }).catch(() => {
    })
  }
}

// 查看发送的消息详情
// const handleViewSentDetails = (row) => {
//   sendMessageDetail(row.id).then(res => {
//     if (res.code === 200) {
//       currentMessage.value = { ...res.data }
//       viewDetailsVisible.value = true
//     }
//   }).catch(() => {
//   })
// }

const closeViewDetails = () => {
  viewDetailsVisible.value = false
  getReceivedList()
  userStore.setUserInfo()
}

// 预览/下载
const handleControlAttachment = (type, url, name) => { 
  if (type === 'preview') {
    // console.log('预览附件:', url)
    filePath.value = url
    viewFileVisible.value = true
  } else if (type === 'download') {
    if (url) {
      saveAs(url, name)
    }
  }
}
// // 接收人列表分页
// const handleRecipientSizeChange = (val) => {
//   recipientPageSize.value = val
// }

// const handleRecipientCurrentChange = (val) => {
//   recipientPageNum.value = val
// }
// 初始化
onMounted(() => {
  getReceivedList()
  getDeptTree()
})
</script>

<style lang="scss" scoped>
.action-container {
  margin-bottom: 10px;
}

.filter-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.message-content {
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-upload__tip) {
  color: #999;
  font-size: 12px;
  margin-left: 20px;
}

.recipient-info {
  display: flex;
  align-items: center;
}
.pagination-container {
  position: relative;
}
/* 弹窗表单样式 */
  .custom-descriptions {
    width: 100%;
  }

  .custom-descriptions .el-descriptions__item {
    display: flex;
    border-bottom: 1px solid #EBEEF5;
  }

  .custom-descriptions .el-descriptions__label {
    width: 120px;
    font-weight: 500;
    color: #606266;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .custom-descriptions .el-descriptions__content {
    flex: 1;
    color: #303133;
    display: flex;
    align-items: center;
    padding: 10px 0 0 10px !important;
  }

  .custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
    border-bottom: none;
  }

  .el-descriptions__cell--label {
    background-color: transparent !important;
  }
  
  :deep(.custom-descriptions .el-descriptions__cell) {
    padding: 11px 11px !important;
  }
  .el-form-item {
    margin-bottom: 0px;
  }
  ::v-deep(.el-form-item__content) {
    margin-left: 0px !important;
  }
</style>
